﻿using NurseStation.DataModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;
using System.Xml.Linq;

namespace NurseStation.common
{
    public class ThemeHelper
    {

        private static readonly Lazy<ThemeHelper> _lazy =
         new Lazy<ThemeHelper>(() => new ThemeHelper(), LazyThreadSafetyMode.PublicationOnly);

        /// <summary>
        /// 单例对象  2022-03-10
        /// </summary>
        public static ThemeHelper Instance
        {
            get
            {
                return _lazy.Value;
            }
        }
        public static DataTemplate GetDataTemplate(string keyname)
        {
            return getDataTemplate(keyname);

            DataTemplate getDataTemplate(params string[] keys)
            {
                foreach (string key in keys)
                {
                    if (TryGetDataTemplate(key, out DataTemplate color))
                    {
                        return color;
                    }
                }
                throw new InvalidOperationException($"找不到指定key对应的资源 '{string.Join(", ", keys)}'");
            }
            bool TryGetDataTemplate(string key, out DataTemplate template)
            {
                if (Application.Current.Resources[key] is DataTemplate temp)
                {
                    template = temp;
                    return true;
                }

                template = null;
                return false;
            }
        }


        public string SettingPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Themes", "BatchVitalSignThemes.xaml");

        public ResourceDictionary CurrResource { get; set; }

        public string CurrXaml { get; set; }
        /// <summary>
        /// 加载列配置主题文件
        /// </summary>
        /// <param name="filePath"></param>
        public void LoadXaml()
        {
            try
            {
                CurrXaml = File.ReadAllText(SettingPath);
                CurrResource = XamlReader.Parse(CurrXaml) as ResourceDictionary;
            }
            catch (Exception e)
            {
                LogHelper.GetLogHelper().Error(e);
            }
        }

        /// <summary>
        /// 重新加载xml获取主题
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public DataTemplate GetDataTemplateFromXml(string key= "BatchVitalSignViewThemes")
        {
            LoadXaml();
            DataTemplate myTemplate = (DataTemplate)CurrResource[key];
            return myTemplate;
        }

        /// <summary>
        /// 将常用转义符转换为原始字符   
        /// </summary>
        /// <param name="text"></param>
        public string EscapeText(string text)
        {
            string result = string.Empty;
            result = text.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "").Replace("&apos;", "'");
            return result;
        }
        /// <summary>
        /// 保存列配置
        /// </summary>
        /// <param name="colSettings"></param>
        public void SaveXaml(List<ColShow> colSettings)
        {
            if (string.IsNullOrEmpty(CurrXaml))
            {
                LoadXaml();
            }
            string gridColumns = GetColumList(colSettings);
            gridColumns = string.Format("<DataGrid.Columns>{0}</DataGrid.Columns>", gridColumns);
            var result = string.Empty;
            string regText = @"<DataGrid.Columns>([\s\S]*?)</DataGrid.Columns>";
            result = Regex.Replace(CurrXaml, regText, gridColumns);
            result = XDocument.Parse(result).ToString();
            result = EscapeText(result);
            //保存
            CurrXaml = result;
            CurrResource = XamlReader.Parse(CurrXaml) as ResourceDictionary;
            File.WriteAllText(SettingPath, result);
           // DataTemplate myTemplate = (DataTemplate)CurrResource[key];
        }

        /// <summary>
        /// 生成配置列
        /// </summary>
        /// <param name="colSettings"></param>
        /// <returns></returns>
        public string GetColumList(List<ColShow> colSettings)
        {
            StringBuilder header = new StringBuilder();
            header.Append(@"<!--日期-->
                        <DataGridTemplateColumn HeaderStringFormat=""RECORD_TIME""   Width=""120"" Header=""日 期"" CanUserSort=""False"" Visibility=""Visible""  >
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation=""Horizontal"" HorizontalAlignment=""Center"">
                                        <TextBlock  VerticalAlignment=""Center"" Text=""{Binding RECORD_TIME,StringFormat=yyyy-MM-dd}"">
                                            <TextBlock.Style>
                                                <Style TargetType=""TextBlock"">
                                                    <Setter Property=""Visibility"" Value=""{Binding IS_SUM, Converter={StaticResource Int2VisibilityConvert},ConverterParameter='hidden'}""></Setter>
                                                </Style>
                                            </TextBlock.Style>
                                        </TextBlock>
                                        <TextBlock  VerticalAlignment=""Center"" Text=""合计:"">
                                            <TextBlock.Style>
                                                <Style TargetType=""TextBlock"">
                                                    <Setter Property=""Visibility"" Value=""{Binding IS_SUM, Converter={StaticResource Int2VisibilityConvert},ConverterParameter='show'}""></Setter>
                                                </Style>
                                            </TextBlock.Style>
                                        </TextBlock>
                                    </StackPanel>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>");

            for (int i = 0; i < colSettings.Count; i++)
            {
                ColShow col = colSettings[i];
                header.Append(@"<!--");
                header.Append(col.FieldName);
                header.Append(@"-->@@");
                header.Append(@"  <DataGridTemplateColumn   MinWidth=""80"" Width=""80"" ");
                if ("是".Equals(col.IfShow))
                {
                    header.Append(@" Visibility=""Visible"" ");
                }
                else
                {
                    header.Append(@" Visibility=""Collapsed"" ");
                }
                header.Append(@">@@");
                header.Append(@"      <DataGridTemplateColumn.Header>@@");
                header.Append(@"          <TextBlock Text =""");
                header.Append(col.Header);
                header.Append(@""" />@@");
                header.Append(@"      </DataGridTemplateColumn.Header>@@");
                header.Append(@"      <DataGridTemplateColumn.CellTemplate>@@");
                header.Append(@"          <DataTemplate>@@");
                header.Append(@"              <TextBlock x:Name=""DropTempText"" Text=""{Binding ");
                header.Append(col.FieldName);
                header.Append(@"}""></TextBlock>@@");
                header.Append(@"          </DataTemplate>@@");
                header.Append(@"      </DataGridTemplateColumn.CellTemplate>@@");
                header.Append(@"      <DataGridTemplateColumn.CellEditingTemplate>@@");
                header.Append(@"          <DataTemplate>@@");
                header.Append(@"              <TextBox VerticalAlignment=""Center"" TextAlignment=""Center""   FocusManager.FocusedElement=""{Binding RelativeSource={RelativeSource Self}}""  Text=""{Binding ");
                header.Append(col.FieldName);
                header.Append(@",UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}""></TextBox>@@");
                header.Append(@"          </DataTemplate>@@");
                header.Append(@"      </DataGridTemplateColumn.CellEditingTemplate>@@");
                header.Append(@"  </DataGridTemplateColumn>@@");

            }

            return header.ToString().Replace("@@", "\n"); ;
        }

    }
}